package cn.kgc.mcartoon.service.impl;

import cn.kgc.mcartoon.dto.ResultDto;
import cn.kgc.mcartoon.entity.MmUsersDO;
import cn.kgc.mcartoon.entity.User;
import cn.kgc.mcartoon.mapper.MmUsersMapper;
import cn.kgc.mcartoon.service.MmUsersService;
import cn.kgc.mcartoon.utils.JwtUtil;
import cn.kgc.mcartoon.utils.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author christopher
 * @since 2021-09-23
 */
@Service
public class MmUsersServiceImpl extends ServiceImpl<MmUsersMapper, MmUsersDO> implements MmUsersService {

    @Autowired
    private MmUsersMapper usersMapper;

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public ResultDto login(MmUsersDO user) {

        log.info(user.getUsername()+"\t"+user.getPassword());
        //将获取的密码使用md5加密传入数据库比较
        user.setPassword(MD5Utils.MD5(user.getPassword()));

        QueryWrapper<MmUsersDO> usersDOQueryWrapper = new QueryWrapper<>(user);

        MmUsersDO loginUser = usersMapper.selectOne(usersDOQueryWrapper);

        if (null != loginUser){
            //生成token
            String jwt = JwtUtil.createJwt(loginUser.getUserid().toString(), loginUser.getUsername(), true);

            Map<String,Object> responseData = new HashMap<>();
            responseData.put("user",loginUser);
            responseData.put("token",jwt);
            System.out.println("aaa"+jwt);
            return ResultDto.ok(responseData);
        }
        return ResultDto.error("用户名或密码错");
    }
}
